package tgc.tdu.tgq.demo.service;

import java.io.File;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import tgc.tdu.tgq.demo.custom.AjaxResult;
import tgc.tdu.tgq.demo.custom.BaseService;
import tgc.tdu.tgq.demo.entity.Student;
import tgc.tdu.tgq.demo.entity.SysRole;
import tgc.tdu.tgq.demo.repository.StudentRepository;
import tgc.tdu.tgq.demo.web.form.StudentForm;

@Service
public class StudentService extends BaseService<Student, Integer>{
	@Value("${web.file_url}")
	private String path;
	
	@Autowired
	private StudentRepository studentDAO;
	@Transactional
	public  AjaxResult upload(StudentForm form) {
		try {
			Student model=new Student();
			Integer id = form.getId();
			if(id!=null) {
				model=findById(id);
			}else {
				model.setPassword(new BCryptPasswordEncoder().encode("1111"));
				model.getRoles().add(new SysRole(3));
			}
			MultipartFile file = form.getFile();
			if(file!=null) {
				String filename = file.getOriginalFilename();
				if(StringUtils.hasText(filename)) {
					String uuid = model.getUuid();
					if(uuid!=null) {
						new File(path,uuid).delete();
					}
					model.setFilename(filename);
					uuid=UUID.randomUUID().toString();
					model.setUuid(uuid);
					file.transferTo(new File(path,uuid));
				}
			}
			BeanUtils.copyProperties(form, model,"id");
			model.setUsername(model.getStuNo());
			
			save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			//return new AjaxResult(false, "数据保存失败");
		}
		return null;
	}

	public List<Student> findByTbClassId(Integer bjId) {
		return studentDAO.findByTbClassId(bjId);
	}

}
